from django.shortcuts import render,HttpResponse
# 加载settings文件
from django.conf import settings
# 加载连接数据库的类
from utils.dbconnect import MysqlConn
# 加载JsonResponse类
from django.http import JsonResponse
# 导入json
import json


# 获取连接数据库的信息
DBS = settings.DATABASES['default']

def china_diff_temp(request):
    """展示中国某一天温差"""
    # 实例化连接数据库
    obj_mysql = MysqlConn(DBS)
    # 准备SQL语句
    sql ="""
    Select province, format((avg(high) - avg(low)),2)As 'diff'  from citys As T1 inner Join weather As T2 on T1.url = T2.url 
    where date='2020-05-15'
    Group by province
    """
    # 开始执行
    obj_mysql.get_db_data(sql)
    # 判断是否成功
    if not obj_mysql.flag:
        return HttpResponse("获取数据出现异常，具体原因：" + str(obj_mysql.msg))
    # 定义个集合
    diff_list = []
    # 开始遍历
    for one in obj_mysql.result:
        temp_dict = {}
        temp_dict['city'] = one[0]
        temp_dict['diff'] = float(one[1])
        # 附加
        diff_list.append(temp_dict)
    # return JsonResponse({'result': obj_mysql.result},json_dumps_params={'ensure_ascii':False})
    return render(request, 'china_diff.html', {'result': diff_list})


